<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="名称">
                <a-input placeholder="请输入优惠券名称" v-model="queryParam.name"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="">
                <a-button type="primary" @click="getList">查询</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>
    <a-card :bordered="false">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <a-radio-group @change="getList" v-model="queryParam.status">
          <a-radio-button :value="-1"> 全部 </a-radio-button>
          <a-radio-button :value="0"> 未开始 </a-radio-button>
          <a-radio-button :value="1"> 进行中 </a-radio-button>
          <a-radio-button :value="2"> 已结束 </a-radio-button>
        </a-radio-group>
        <div class="table-operator" style="margin: 0">
          <a-button type="primary" @click="showEditCoupon = true" icon="plus">新建</a-button>
          <a-popconfirm title="确认删除所选项吗？" @confirm="handleMenuClick">
            <a-button> 批量删除 </a-button>
          </a-popconfirm>
        </div>
      </div>
      <a-table
        :rowKey="
          (r, i) => {
            return r.id
          }
        "
        :pagination="{
          total: this.totalCount,
          showSizeChanger: false,
          onChange: this.tablePageChange,
        }"
        :columns="columns"
        :data-source="list"
        :scroll="{ x: 'max-content' }"
        style="margin-top: 16px"
      >
        <a-popconfirm
          placement="topLeft"
          slot="status"
          slot-scope="text, record"
          ok-text="确定"
          cancel-text="取消"
          @confirm="changeShow(record)"
        >
          <template slot="title">
            <p>{{ text == 1 ? '是否确定不显示' : '是否确定显示' }}</p>
          </template>
          <a-tag :color="text == 1 ? 'blue' : 'red'">{{ text | statusFilter }}</a-tag>
        </a-popconfirm>
        <!-- 最低消费金额 -->
        <span slot="min_price" slot-scope="text"> {{ text }}元 </span>

        <!-- 优惠券金额 -->
        <span slot="sub_price" slot-scope="text">{{ text }}元</span>

        <!-- 折扣率 -->
        <span slot="discount" slot-scope="text">{{ text }}折</span>

        <!-- 已领 -->
        <div slot="total_count" slot-scope="text, item">
          <span>{{ item.receive_count }}</span>
        </div>

        <!-- 剩余 -->
        <div slot="surplus_count" slot-scope="text">
          <span v-if="text >= 0">{{ text }}</span>
          <span v-else>无限制</span>
        </div>

        <!-- 有效期 -->
        <div slot="expire_type" slot-scope="text, item">
          <span v-if="item.expire_type == 1 && item.expire_day != 0"> 领卷后当日起{{ item.expire_day }}天内可用 </span>
          <span v-else-if="item.expire_type == 1 && item.expire_day == 0">永久生效</span>
          <span v-if="item.expire_type == 2">{{ item.begin_time }}至{{ item.end_time }}</span>
        </div>

        <!-- 优惠卷数量 -->
        <div slot="coupon_status" slot-scope="text">
          <div v-if="text == 0" class="coupon-status-1">未开始</div>
          <div v-if="text == 1" class="coupon-status-1">进行中</div>
          <div v-if="text == 2" class="coupon-status-2">已结束</div>
        </div>

        <!-- 操作按钮 -->
        <span slot="action" slot-scope="text, record">
          <a-button type="link" @click="handleEdit(record)" size="small">编辑</a-button>
          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link" @click="(e) => e.preventDefault()"> 更多<a-icon type="down" /> </a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a-button
                  type="link"
                  @click="$router.push({ name: 'SaasCouponDetail', query: { id: record.id } })"
                  size="small"
                  >详情</a-button
                >
              </a-menu-item>
              <!-- <a-menu-item>
                <a-button type="link" @click="couponSend(record)" size="small">发放</a-button>
              </a-menu-item>
              <a-menu-item>
                <a-button type="link" @click="clickQrcode(record.id)" size="small">小程序二维码</a-button>
              </a-menu-item> -->
              <a-menu-item>
                <a-popconfirm title="确认删除该优惠券吗？" placement="left" @confirm="handleDelete(record)">
                  <a-button type="link" size="small">删除</a-button>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
      </a-table>
    </a-card>
    <!-- 创建优惠券 -->
    <a-modal
      :title="!couponForm.id ? '创建优惠券' : '编辑优惠券'"
      :width="800"
      :confirm-loading="btnLoading"
      :mask-closable="false"
      :destroy-on-close="true"
      :bodyStyle="{ height: '600px', overflow: 'auto' }"
      v-model="showEditCoupon"
      @ok="editCoupon"
      :afterClose="closeModal"
    >
      <a-form-model
        ref="couponForm"
        :model="couponForm"
        :rules="couponRules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 14 }"
      >
        <a-form-model-item label="优惠券名称" prop="name">
          <a-input v-model="couponForm.name" placeholder="请输入优惠券名称" />
        </a-form-model-item>
        <a-form-model-item label="优惠券用途" prop="business_type">
          <a-radio-group v-model="couponForm.business_type">
            <a-radio value="1"> 领券中心 </a-radio>
            <a-radio value="2"> 会员卡赠送 </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="优惠券类型" prop="discount_type">
          <a-radio-group v-model="couponForm.discount_type">
            <a-radio value="1"> 折扣券 </a-radio>
            <a-radio value="2"> 满减券 </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item
          label="优惠金额"
          prop="sub_price"
          v-if="couponForm.discount_type == 2"
          extra="优惠券只能抵消商品金额，不能抵消运费，商品金额最多优惠到0.01元"
        >
          <a-input-number
            placeholder="优惠金额"
            :formatter="(value) => `${value}元`"
            :parser="(value) => value.replace('元', '')"
            :min="0"
            :precision="2"
            :step="0.01"
            v-model="couponForm.sub_price"
          />
        </a-form-model-item>
        <a-form-model-item
          label="折扣率"
          prop="discount"
          v-if="couponForm.discount_type == 1"
          extra="如打8.5折请填写8.5，如不打折请填写10支持折扣率0.1-10"
        >
          <a-input-number
            placeholder="折扣率"
            :formatter="(value) => `${value}折`"
            :parser="(value) => value.replace('折', '')"
            :min="0"
            :precision="2"
            :step="0.01"
            v-model="couponForm.discount"
          />
        </a-form-model-item>
        <a-form-model-item
          label="最低消费金额"
          prop="min_price"
          extra="购物金额（不含运费）达到最低消费金额才可使用优惠券，无门槛优惠券请填0"
        >
          <a-input-number
            placeholder="最低消费金额"
            :formatter="(value) => `${value}元`"
            :parser="(value) => value.replace('元', '')"
            :min="0"
            :precision="2"
            :step="0.01"
            v-model="couponForm.min_price"
          />
        </a-form-model-item>
        <a-form-model-item label="到期类型" prop="expire_type">
          <a-radio-group v-model="couponForm.expire_type">
            <a-radio value="1"> 领取后N天内有效 </a-radio>
            <a-radio value="2"> 时间段 </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="有效天数" prop="expire_type" v-if="couponForm.expire_type == 1">
          <a-input-number placeholder="有效天数" :min="0" v-model="couponForm.expire_day" />
        </a-form-model-item>
        <a-form-model-item label="有效期范围" prop="expire_date" v-if="couponForm.expire_type == 2">
          <a-range-picker
            :format="'YYYY-MM-DD'"
            :valueFormat="'YYYY-MM-DD'"
            v-model="expire_date"
            @change="changeTime"
          />
        </a-form-model-item>
        <a-form-model-item label="是否可线上领取" prop="is_join">
          <a-radio-group v-model="couponForm.is_join">
            <a-radio value="1"> 否 </a-radio>
            <a-radio value="2"> 是 </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="发放总数" prop="total_count" v-if="couponForm.is_join == 2">
          <a-input-number placeholder="发放总数" :min="-1" v-model="couponForm.total_count" />
        </a-form-model-item>
        <a-form-model-item label="排序" prop="sort">
          <a-input-number placeholder="排序" :min="0" v-model="couponForm.sort" />
        </a-form-model-item>
        <a-form-model-item label="指定类型" prop="appoint_type">
          <a-radio-group v-model="couponForm.appoint_type">
            <a-radio value="1"> 商品类别 </a-radio>
            <a-radio value="2"> 商品 </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item
          label="商品类别"
          prop="cat_id_list"
          extra="不添加表示全场通用"
          v-if="couponForm.appoint_type == 1"
        >
          <a-button @click="showAddCat = true">选择类别</a-button>
          <SelectCat v-model="showAddCat" @onOk="selectGoodsCatOk"></SelectCat>
          <div v-if="cat_list && cat_list.length > 0" class="chhhhhhhh" style="width: 100%">
            <div style="float: left; width: 60px; margin: 5px 10px" v-for="(item, index) in cat_list" :key="index">
              <div style="width: 100%; height: 60px">
                <img width="100%" height="100%" :src="item.pic_url" alt="" />
              </div>
              <div style="width: 100%; text-align: center">{{ item.name }}</div>
            </div>
          </div>
        </a-form-model-item>
        <a-form-model-item
          label="添加商品"
          prop="appoint_type"
          extra="不添加表示全场通用"
          v-if="couponForm.appoint_type == 2"
        >
          <a-button @click="showAddGoods = true">选择商品</a-button>
          <SelectGoods v-model="showAddGoods" @onOk="selectGoodsOk"></SelectGoods>
          <div v-if="goods_list && goods_list.length > 0" style="width: 100%">
            <div style="float: left; width: 60px; margin: 5px 10px" v-for="(item, index) in goods_list" :key="index">
              <div style="width: 100%; height: 60px">
                <img width="100%" height="100%" :src="item.cover_pic" alt="" />
              </div>
              <div style="width: 100%; text-align: center; overflow: hidden; height: 40px">{{ item.name }}</div>
            </div>
          </div>
        </a-form-model-item>
        <a-form-model-item
          label="是否可转增"
          prop="is_give"
          extra="如果选择是，用户获得优惠券后，可以将优惠券转增分享给好友，好友打开链接后， 如好友是新用户可绑定上下级关系"
        >
          <a-radio-group v-model="couponForm.is_give">
            <a-radio value="1"> 是 </a-radio>
            <a-radio value="0"> 否 </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="使用说明" prop="rule">
          <a-textarea :rows="2" v-model="couponForm.rule" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </page-header-wrapper>
</template>


<script>
import SelectCat from '@/components/SearchCat/index'
import SelectGoods from '@/components/SearchGoods/index'
import {
  couponList,
  couponDel,
  couponAdd,
  couponEdit,
  couponSendUser,
  couponDels,
  couponStatus,
  couponQrcode,
} from '@/api/marketing'
const columns = [
  {
    title: '优惠券ID',
    dataIndex: 'id',
  },
  {
    title: '优惠券名称',
    dataIndex: 'name',
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
  },
  {
    title: '最低消费',
    dataIndex: 'min_price',
    scopedSlots: {
      customRender: 'min_price',
    },
    sorter: (a, b) => a.min_price - b.min_price,
  },
  {
    title: '优惠方式',
    dataIndex: 'discount_type_text',
    scopedSlots: {
      customRender: 'discount_type_text',
    },
  },
  {
    title: '优惠券金额',
    dataIndex: 'sub_price',
    scopedSlots: {
      customRender: 'sub_price',
    },
    sorter: (a, b) => a.sub_price - b.sub_price,
  },
  {
    title: '折扣率',
    dataIndex: 'discount',
    scopedSlots: {
      customRender: 'discount',
    },
    sorter: (a, b) => a.discount - b.discount,
  },
  {
    title: '已领',
    dataIndex: 'total_count',
    scopedSlots: {
      customRender: 'total_count',
    },
    // 总数减剩余为已领   剩余默认是-1  总数默认是 -1
    sorter: (a, b) => a.total_count - a.surplus_count - (b.total_count - b.surplus_count),
  },
  {
    title: '剩余',
    dataIndex: 'surplus_count',
    scopedSlots: {
      customRender: 'surplus_count',
    },
    sorter: (a, b) => a.surplus_count - b.surplus_count,
  },

  {
    title: '有效时间',
    dataIndex: 'expire_type',
    scopedSlots: {
      customRender: 'expire_type',
    },
  },
  {
    title: '状态',
    dataIndex: 'coupon_status',
    scopedSlots: {
      customRender: 'coupon_status',
    },
  },
  {
    title: '操作',
    width: '150px',
    dataIndex: 'action',
    scopedSlots: {
      customRender: 'action',
    },
  },
]
export default {
  components: {
    SelectCat,
    SelectGoods,
  },
  data() {
    let checkDate = (rule, value, callback) => {
      if (this.couponForm.expire_type == 2) {
        if (!this.couponForm.begin_time || !this.couponForm.end_time) {
          console.log(this.couponForm, '112')
          callback(new Error('请选择有效时间'))
        } else {
          console.log(this.couponForm, 232)
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      queryParam: {
        name: '',
        status: -1,
        is_business: 1,
        pageNo: 1,
        pageSize: 10,
        business_type: 0,
      },
      list: [],
      columns,
      // 是否显示新增 编辑优惠券弹窗
      showEditCoupon: false,
      // 添加 编辑优惠券表单
      couponForm: {
        id: '',
        name: '',
        discount_type: '2',
        sub_price: '',
        discount: 10,
        min_price: 0,
        expire_type: '1',
        expire_day: 0,
        begin_time: null,
        end_time: null,
        is_join: '1',
        total_count: -1,
        sort: 0,
        appoint_type: '1',
        goods_id_list: '',
        cat_id_list: '',
        is_give: '0',
        rule: '',
        is_business: '1',
        business_type: '1',
      },
      // 优惠券表单规则
      couponRules: {
        name: [{ required: true, message: '请输入优惠券名称', trigger: 'blur' }],
        discount_type: [{ required: true, message: '请选择优惠券类型', trigger: 'change' }],
        rule: [{ required: true, message: '请输入使用说明', trigger: 'blur' }],
        expire_date: [{ validator: checkDate }],
      },
      btnLoading: false,
      // 选择的商品列表
      goods_list: [],
      // 选择的分类列表
      cat_list: [],
      // 是否显示选择类别弹窗
      showAddCat: false,
      // 是否显示选择商品弹窗
      showAddGoods: false,
      // 数据总数
      totalCount: 0,
      // 选中的时间段
      expire_date: [],
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 关闭弹窗的回调
    closeModal() {
      this.couponForm.id = ''
      this.couponForm.name = ''
      this.couponForm.discount_type = '2'
      this.couponForm.sub_price = ''
      this.couponForm.discount = '10'
      this.couponForm.min_price = '0'
      this.couponForm.expire_type = '1'
      this.couponForm.expire_day = '0'
      this.couponForm.begin_time = null
      this.couponForm.end_time = null
      this.expire_date = []
      this.couponForm.is_join = '1'
      this.couponForm.total_count = '-1'
      this.couponForm.sort = '0'
      this.couponForm.appoint_type = '1'
      this.couponForm.goods_id_list = ''
      this.couponForm.cat_id_list = ''
      this.couponForm.is_give = '0'
      this.couponForm.rule = ''
      this.couponForm.is_business = '1'
      this.couponForm.business_type = '1'
    },
    // 选择类别回调
    selectGoodsCatOk(e) {
      console.log(e)
      this.cat_list = e
      this.couponForm.cat_id_list = JSON.stringify(this.cat_list.map((el) => el.id))
    },
    // 选择商品回调
    selectGoodsOk(e) {
      console.log(e)
      this.goods_list = e
      this.couponForm.goods_id_list = JSON.stringify(this.goods_list.map((el) => el.id))
    },
    // 添加编辑优惠券
    editCoupon() {
      this.$refs.couponForm.validate(async (valid) => {
        if (valid) {
          if (!this.couponForm.id) {
            const res = await couponAdd(this.couponForm)
            if (res.code == 0) {
              this.showEditCoupon = false
              this.getList()
            }
          } else {
            const res = await couponEdit(this.couponForm)
            if (res.code == 0) {
              this.showEditCoupon = false
              this.getList()
            }
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 获取优惠券列表
    async getList() {
      const hide = this.$message.loading('加载中...', 1000)
      const res = await couponList(this.queryParam)
      if (res.code == 0) {
        this.list = res.data.data
        this.totalCount = res.data.count
      }
      hide()
    },
    // 分页查询
    tablePageChange(e) {
      this.queryParam.pageNo = e
      this.getList()
    },
    // 切换时间
    changeTime(e) {
      if (e.length) {
        this.couponForm.begin_time = e[0]
        this.couponForm.end_time = e[1]
      } else {
        this.couponForm.begin_time = null
        this.couponForm.end_time = null
      }
    },
    // 点击编辑优惠券
    handleEdit(record) {
      this.couponForm.id = record.id
      this.couponForm.name = record.name
      this.couponForm.discount_type = record.discount_type
      this.couponForm.sub_price = record.sub_price
      this.couponForm.discount = record.discount
      this.couponForm.min_price = record.min_price
      this.couponForm.expire_type = record.expire_type
      this.couponForm.expire_day = record.expire_day
      this.couponForm.begin_time = record.begin_time
      this.couponForm.end_time = record.end_time
      if (this.couponForm.expire_type == 2) {
        this.expire_date = [record.begin_time, record.end_time]
      }
      this.couponForm.is_join = record.is_join
      this.couponForm.total_count = record.total_count
      this.couponForm.sort = record.sort
      this.couponForm.appoint_type = record.appoint_type
      this.couponForm.goods_id_list = record.goods_id_list
      this.couponForm.cat_id_list = record.cat_id_list
      this.couponForm.is_give = record.is_give
      this.couponForm.rule = record.rule
      this.couponForm.is_business = record.is_business
      this.couponForm.business_type = record.business_type
      this.showEditCoupon = true
    },
    // 点击删除优惠券
    async handleDelete(record) {
      const res = await couponDel({
        key: record.id,
      })
      if (res.code == 0) {
        this.getList()
      }
    },
  },
}
</script>

<style lang="less" scoped>
</style>